import React from 'react';
import AnswerEdit from '@/pages/KnowledgeManagement/Overview/EditingKnowledge/answerEdit';
import AnswerBack from '@/pages/KnowledgeManagement/Overview/EditingKnowledge/answerBack';
import { Button, Col, message, Row } from 'antd';
import AnswerSlot from '@/pages/KnowledgeManagement/Overview/EditingKnowledge/answerSlot';

class AnswerModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      answerArr: [
        {
          isDefault: true,
          content: '',
          answerType: 'richText',
          slotValues: [],
          isEdit: true,
          slotDetailArr: [],
        },
      ],
      answerBack: [
        {
          isDefault: true,
          content: '',
          answerType: 'richText',
          slotValues: [],
          isEdit: true,
          slotDetailArr: [],
        },
      ],
    };
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  setAnswerData = data => {
    this.setState({
      answerArr: data,
      answerBack: data,
    });
  };

  checkTab = (key, index, type) => {
    let { answerArr } = this.state;
    answerArr[index].answerType = key;
    if (type === 'richText') {
      answerArr[index].content = this.AnswerEdit.getRichTextContent(index);
    }
    this.setState({
      answerArr,
      answerBack: answerArr,
    });
  };

  textChangeValue = (e, index) => {
    let { answerArr } = this.state;
    const value = e.target.value;
    answerArr[index].content = value;
    this.setState({ answerArr, });
  };

  completeContent = index => {
    let { answerArr } = this.state;

    if (answerArr[index].answerType === 'richText') {
      answerArr[index].content = this.refs[`edit${index}`]?.refs[`content${index}`]?.getUeditorContent();
    }
    if (!answerArr[index].isDefault) {
      if (answerArr[index].slotValues.length === 0) {
        return message.error('词槽答案词槽不允许为空，请添加词槽再保存');
      }
      if (!answerArr[index].content || answerArr[index].content === '') {
        return message.error('词槽答案的答案不允许为空，请添加答案再保存');
      }
    } else {
      if (!answerArr[index].content || answerArr[index].content === '') {
        return message.error('答案不允许为空，请添加答案再保存');
      }
    }
    answerArr[index].isEdit = false;
    answerArr[index].hasBeenCompleted = true;
    // console.log(answerArr);
    this.setState({
      answerArr,
      answerBack: answerArr,
    });
  };

  editAnswer = index => {
    let { answerArr } = this.state;
    answerArr[index].isEdit = true;
    // console.log(answerArr);
    this.setState({ answerArr, }, () => {
      if (!answerArr[index].isDefault) {
        const slotList = this.props.slotData;
        let ids = slotList.map(item => item.id);
        this.props.getSlotDetailById(ids, index);
      }
    });
  };

  removeAnswer = index => {
    let { answerArr } = this.state;
    const arr = answerArr.filter((item, i) => i != index);
    this.setState({ answerArr: arr, });
  };

  cancelContent = index => {
    let { answerBack, answerArr } = this.state;
    answerArr[index].isEdit = !answerArr[index].isEdit;
    this.setState({ answerArr, }, () => {
      this.doCancel(index);
    });
  };

  doCancel = index => {
    const arr_bak = this.state.answerBack;
    const arr = this.state.answerArr;
    const isDefault = arr_bak[index].isDefault;
    const isEdit = arr_bak[index].isEdit;
    const hasBeenCompleted = arr_bak[index].hasBeenCompleted;
    if (!isDefault) {
      if (!hasBeenCompleted) {
        arr_bak.splice(index, 1);
        arr.splice(index, 1);
        this.setState({
          answerBack: arr_bak,
          answerArr: arr,
        });
      }
    }
  };

  addAnswer = () => {
    let { answerArr } = this.state;
    const obj = {
      isDefault: false,
      content: '',
      answerType: 'richText',
      slotValues: [],
      isEdit: true,
      slotDetailArr: [],
    };
    answerArr.push(obj);
    this.setState({
      answerArr,
      answerBack: answerArr,
    });
  };

  selectSlot = (value, index, slotIndex, id, name, keyName) => {
    let { answerArr } = this.state;
    let oldSlotArr = answerArr[index].slotValues;
    const result = oldSlotArr.filter(item => item.id === id);
    if (result.length > 0) {
      for (let oldSlotItem of oldSlotArr) {
        if (oldSlotItem.id === id) {
          oldSlotItem.values = value;
        }
      }
    } else {
      oldSlotArr.push({
        id: id,
        values: value,
        slotName: name,
        keyName,
      });
    }
    this.setState({ answerArr, });
  };

  render() {
    const { answerArr } = this.state;
    const { slotDetailArr } = this.props;
    return answerArr.map((item, index) => {
      return (
        <div key={index}>
          {item.isEdit ? (
            <div style={{ border: '1px solid #ccc', borderRadius: '16px', padding: 10, marginTop: 10 }}>
              <Row>
                <Col span={14}>
                  {item.isDefault ? ('') : (
                    <AnswerSlot
                      slotDetailArr={slotDetailArr}
                      index={index}
                      selectSlot={this.selectSlot}
                      answer={item}
                    />
                  )}
                </Col>
                <Col span={10} style={{ textAlign: 'right' }}>
                  <Button style={{ marginRight: 10 }} onClick={() => this.cancelContent(index)}>
                    取消
                  </Button>
                  <Button type={'primary'} onClick={() => this.completeContent(index)}>
                    完成
                  </Button>
                </Col>
              </Row>
              <AnswerEdit
                onRef={ref => (this.AnswerEdit = ref)}
                answer={item}
                index={index}
                checkTab={this.checkTab}
                textChangeValue={this.textChangeValue}
                ref={`edit${index}`}
              />
            </div>
          ) : (
            <div style={{ margin: '10px 0' }}>
              <AnswerBack
                onRef={ref => (this.AnswerBack = ref)}
                answer={item}
                index={index}
                editAnswer={this.editAnswer}
                removeAnswer={this.removeAnswer}
              />
            </div>
          )}
        </div>
      );
    });
  }
}

export default AnswerModal;
